<?php
namespace App\Http\Controllers\Auth;

use App\Exceptions\CustomException;
use App\Helpers\JwtHelper;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Helpers\AuthHelper;
use App\Http\Controllers\BaseController;
use App\Models\LoginModel;
use App\Services\Common\UserService;
use App\Helpers\CodeHelper;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;


class LoginController extends Controller
{
    /**
     * 获取验证码
     * @return mixed
     */
    public function captcha()
    {
        return $this->system_output(app('captcha')->create('default', true));
    }

    public function showLogin(Request $request)
    {
        var_dump(11);die;
        //return view('auth.login');
        return view('admin.login_register.login');
    }

    public function submitLogin(Request $request)
    {
        if($request->isMethod('POST')){

        }
        $params = $request->all();
        var_dump(11);die;
        // 测试环境去掉验证码验证
        $app_config = config('app');
        $valida_arr = [
            'username'  => 'required',
            'password'  => 'required',
//            'captcha'   => 'required',
//            'key'   => 'required'
        ];
        if ($app_config['env'] == 'local') {
            $valida_arr = [
                'username'  => 'required',
                'password'  => 'required'
            ];
        }

        $validator = Validator::make($params, $valida_arr,[
            'username.*' => '请输入用户名',
            'password.*' => '请输入密码',
//            'captcha.*'  => '请输入验证码',
//            'key.*'      => '无效的验证码'
        ]);

        if ($validator->fails()) {
            return $this->system_output($validator->errors(), CodeHelper::SYSTEM_VALIDATOR_ERROR);
        }
        if($app_config['env'] != 'local' && !captcha_api_check($params['captcha'], $params['key'])) {
            return $this->system_output([], CodeHelper::SYSTEM_CAPTCHA_CODE_ERROR);
        }
        $login = DB::table('tbl_login')->where(['mobile' => $params['username'],'status'=>9])->first();

        // 查找用户
        if (empty($login)) {
            return $this->system_output([], CodeHelper::SYSTEM_LOGIN_ERROR);
        }

        // 校验密码
        $LoginModel = new LoginModel();
        $result = $LoginModel->checkPassword($params['password'],$login->password);

        if ($result == false) {
            return $this->system_output([], CodeHelper::SYSTEM_LOGIN_ERROR);
        }

        // 查找用户信息
        $field = ['user_id', 'role_id', 'user_type', 'username','department_id'];
        $user = UserService::getOne(['user_id' => $login->user_id], $field);

        $this->user_id = $user['user_id'];

        if (!$this->isLogin()) {
            $this->loginByJwt($user);
        }


        $request->session()->put('uid',$user['user_id']);
        $request->session()->put('user',$user);
        //$arr = $this->preResponse($request->all());
        // 缓存权限数据
        // $auth = new AuthHelper($user, true);

        //var_dump($request->session()->has('uid'));die;
        // $data = $request->session()->put('uid',$this->user_id);

        return $this->output(['token'=>$this->token], 'login__success');

    }

    /**
     * 用户登录
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws CustomException
     */
    public function login(Request $request)
    {

        $params = $request->all();

        // 测试环境去掉验证码验证
        $app_config = config('app');
        $valida_arr = [
            'username'  => 'required',
            'password'  => 'required',
            'captcha'   => 'required',
            'key'   => 'required'
        ];
        if ($app_config['env'] == 'local') {
            $valida_arr = [
                'username'  => 'required',
                'password'  => 'required'
            ];
        }

        $validator = Validator::make($params, $valida_arr,[
            'username.*' => '请输入用户名',
            'password.*' => '请输入密码',
            'captcha.*'  => '请输入验证码',
            'key.*'      => '无效的验证码'
        ]);

        if ($validator->fails()) {
            return $this->system_output($validator->errors(), CodeHelper::SYSTEM_VALIDATOR_ERROR);
        }

        if($app_config['env'] != 'local' && !captcha_api_check($params['captcha'], $params['key'])) {
            return $this->system_output([], CodeHelper::SYSTEM_CAPTCHA_CODE_ERROR);
        }

        $res = LoginModel::where(['loginname' => $params['username'], 'status' => 9])->get();
        // 查找用户
        if (empty($res)) {
            return $this->system_output([], CodeHelper::SYSTEM_LOGIN_ERROR);
        }
        $login = $res[0];
        // 校验密码
        $result = $login->checkPassword($params['password']);
        if ($result == false) {
            return $this->system_output([], CodeHelper::SYSTEM_LOGIN_ERROR);
        }
        // 查找用户信息
        $field = ['user_id', 'role_id', 'user_type', 'username'];
        $user = UserService::getOne(['user_id' => $login->user_id], $field);
        $this->user_id = $user['user_id'];
        if (!$this->isLogin()) {
            $this->loginByJwt($user);
        }

        // 缓存权限数据
        // $auth = new AuthHelper($user, true);
        return $this->output(['token'=>$this->token], 'login__success');
    }

    public function logout(Request $request)
    {
        $uid = $request->session()->get('uid');
        $result = Session::forget('uid');
        if($uid){
            return json_encode(['code'=>0,'errmsg'=>'退出成功']);
        }else{
            return json_encode(['code'=>206,'errmsg'=>'失败']);
        }

    }
    public function password(Request $request) {
        if($request->isMethod('POST')) {

            $request = app('request');
            $validator = Validator::make($request->all(), [
                'old_pass' => 'required|max:255',
                'new_pass' => 'required|min:5|max:20',
            ]);
            if ($validator->fails()) {
                return json_encode(['code'=>222,'errmsg'=>'密码不正确，请重新输入,至少5位']);
            }

            $admin_id = $request->session()->get('uid');
            $adminUser = DB::table('tbl_login')->where(['user_id'=>$admin_id,'status'=>9])->first();

            if (!$adminUser) {
                self::apiException(ApiStatusCode::UNAUTHENTICATED, '账号不存在');
            }


            $old_pass = $request->input('old_pass');
            $new_pass = $request->input('new_pass');
            if(!LoginModel::checkPassword($old_pass,$adminUser->password)){
                return json_encode(['code'=>222,'errmsg'=>'原密码不正确']);
            }

            $update = array('password'  =>md5($new_pass));
            $result = DB::table('tbl_login')->where('user_id',$admin_id)->update($update);
            if($result){
                return json_encode(['code'=>0,'errmsg'=>'修改成功']);
            }else{
                return json_encode(['code'=>201,'errmsg'=>'修改失败']);
            }

        }
        return view('auth.password');
    }
}
